package org.zhiyootech.resources;

import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.zhiyootech.base.annotation.Login;
import org.zhiyootech.base.domain.R;
import org.zhiyootech.base.enums.ChannelEnums;
import org.zhiyootech.base.enums.ErrorEnums;
import org.zhiyootech.domain.LoginRequest;
import org.zhiyootech.entity.UserInfo;
import org.zhiyootech.service.UserInfoService;

import javax.annotation.security.PermitAll;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import org.zhiyootech.base.jwt.*;
import org.zhiyootech.utils.JsonUtils;

import java.util.Date;
import java.util.HashMap;

@Slf4j
@Path("/login")
@RequestScoped
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class WeChartLoginResource {

    @Inject
    GenerateToken generateToken;
    @Inject
    UserInfoService userInfoService;
    @ConfigProperty(name = "app.id")
    String appId;
    @ConfigProperty(name = "app.secret")
    String appSecret;
    @ConfigProperty(name = "app.request.url")
    String appRequestUrl;

    /**
     * 获取openID
     *
     * @param loginRequest
     * @return R
     */
    @POST
    @Path("/we-chart/v1")
    @PermitAll
    @Login(isLogin = false)
    public R getOpenId(@Valid LoginRequest loginRequest) {
        try {
            HashMap<String, Object> requestOpenParamMap = Maps.newHashMap();
            requestOpenParamMap.put("appid", appId);
            requestOpenParamMap.put("secret", appSecret);
            requestOpenParamMap.put("js_code", loginRequest.getCode());
            requestOpenParamMap.put("grant_type", "authorization_code");
            String res = HttpUtil.get(appRequestUrl, requestOpenParamMap);
            HashMap<String, String> hashMap = JsonUtils.toBean(res, HashMap.class);
            String openId = hashMap.get("openid");
            UserInfo userRecord = userInfoService.findByOpenId(openId);
            if (null != userRecord) {
                return R.builder()
                        .token(generateToken.generateTokenByUserInfo(userRecord.getNickName()))
                        .build()
                        .ok();
            } else {
                log.info("没有发现该openId对应对客户记录");
                UserInfo userInfo = new UserInfo();
                BeanUtils.copyProperties(userInfo, loginRequest);
                userInfo.setChannel(ChannelEnums.WE_PROGRAM.getChannelCode());
                userInfo.setCreated(new Date());
                userInfo.setModified(new Date());
                userInfo.setOpenId(openId);
                boolean save = userInfoService.save(userInfo);
                if (save) {
                    log.info("保存新客户记录成功");
                    return R.builder()
                            .token(generateToken.generateTokenByUserInfo(userInfo.getNickName()))
                            .build()
                            .ok();
                }
                log.error(ErrorEnums.GET_OPEN_ID_FAIL.getMessage());
                return R.builder()
                        .message(ErrorEnums.SAVE_CUSTOMER_INFO_FAIL.getMessage())
                        .build()
                        .fail();
            }
        } catch (Exception e) {
            log.error(ErrorEnums.GET_OPEN_ID_FAIL.getCode(), e);
            return R.builder()
                    .message(ErrorEnums.GET_OPEN_ID_FAIL.getMessage())
                    .build()
                    .fail();
        }
    }

}
